# -*- coding:utf-8 -*-
'''音频截取窗口'''
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import tkinter.messagebox
import tkinter as tk
from tkinter import filedialog
from media import basic
import os
import subprocess
import re
from media import mediaUtil
import threading

class acutFrame(object):
    def __init__(self,parent):
        self.root = tkinter.Toplevel(parent)
        self.root.title('音频截取')
         #子窗口随着主窗口关闭或最小化
        self.root.transient(parent)
        self.root.resizable(False, False)
        self.root.minsize(500, 180)
        self.centerWin(self.root,500, 180)
        
        #用于保存音频长度（单位：秒）
        self.d_second=None
        
        cutFrame = ttk.Frame(self.root)
        bm = PhotoImage(file = mediaUtil.SOURCE_PATH+'audio-cut.png')
        tipLabel = Label(cutFrame,image=bm)
        tipLabel.bm = bm
        tipLabel.grid(row=0,rowspan=7,column=0,padx=5,pady=5,sticky=(N, W, E, S))
        
        audioLabel = Label(cutFrame,text='音频文件：')
        audioLabel.grid(column=1, row=2,padx=3,sticky=(N, W, E, S))
        self.audioString = StringVar()
        self.audioPath = Entry(cutFrame,textvariable = self.audioString,width=30,state=DISABLED)
        self.audioPath.grid(column=2, row=2,padx=3,sticky=(W, E))
        audioPathBtn = ttk.Button(cutFrame,text="选择文件",width=10,command=self.getaudioPath).grid(row=2,column=3,sticky=W+E,padx=10)
        
        outLabel = Label(cutFrame,text='存放文件夹：')
        outLabel.grid(column=1, row=3,padx=3,sticky=(N, W, E, S))
        self.audio2String = StringVar()
        self.audio2Path = Entry(cutFrame,textvariable = self.audio2String,width=30,state=DISABLED)
        self.audio2Path.grid(column=2, row=3,padx=3,sticky=(W, E))
        audioPathBtn = ttk.Button(cutFrame,text="选择文件夹",width=10,command=self.getaudio2Path).grid(row=3,column=3,sticky=W+E,padx=10)

        startLabel = Label(cutFrame,text='开始时间：')
        startLabel.grid(column=1, row=5,padx=5,sticky=(N, W, E, S))
        self.startTime = Scale(cutFrame, from_=0, to=100,orient=HORIZONTAL,command=self.getStartScale)
        self.startTime.grid(column=2, row=5,padx=5,sticky=(W, E))
        self.startShowLabel = Label(cutFrame,text='00:00:00')
        self.startShowLabel.grid(column=3, row=5,padx=5,sticky=(N, W, E, S))

        endLabel = Label(cutFrame,text='结束时间：')
        endLabel.grid(column=1, row=7,padx=5,sticky=(N, W, E, S))
        self.endTime = Scale(cutFrame, from_=0, to=100, orient=HORIZONTAL,command=self.getEndScale)
        self.endTime.grid(column=2, row=5,padx=5,sticky=(W, E))
        self.endTime.grid(column=2, row=7,padx=5,sticky=(W, E))
        self.endShowLabel = Label(cutFrame,text='00:00:00')
        self.endShowLabel.grid(column=3, row=7,padx=5,sticky=(N, W, E, S))
        
        vduration = Label(cutFrame,text='音频总时长：')
        vduration.grid(column=1, row=8,padx=5,sticky=(N, W, E, S))
        self.vdduration = Label(cutFrame,text='')
        self.vdduration.grid(column=2, row=8,padx=5,sticky=(N, W, E, S))
        self.execBtn = ttk.Button(cutFrame,text="截取",width=10,command=self.audioCut)
        self.execBtn.grid(row=8,column=3,sticky=W+E,padx=10)
        
        self.statusLabel = Label(cutFrame,text='已就绪',relief=GROOVE,anchor=W)
        self.statusLabel.grid(row=9,column=0,columnspan=4,pady=5,sticky=(N, W, E, S))
        
        cutFrame.grid(row=0,column=0,pady=5,sticky=(N, W, E, S))
    
    '''窗口居中'''
    def centerWin(self,root,width,height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)  
        root.geometry(size)
    
    '''获取音频文件地址'''
    def getaudioPath(self):
        self.audioString.set('')
        path = filedialog.askopenfilename()
        if path !="":
            ext = os.path.splitext(path)[1][1:]
            isaudio = 0
            for et in basic.AUDIOS:
                if et == ext:
                    isaudio = 1
            if isaudio == 1:
                self.audioString.set(path)
                cmd = mediaUtil.cmd_mediaInfo(path)
                if cmd == None:
                    tkinter.messagebox.showerror("提示","无法获取音频信息命令")
                    return Flase
                subprocess.call(cmd)
                result = subprocess.getoutput(cmd)
                d = re.search(r'Duration: (\d+):(\d+):(\d+).(\d+),', result)
                duration= '{0}:{1}:{2}'.format(d.group(1),d.group(2),d.group(3))
                #获取音频长度秒数
                self.d_second = mediaUtil.getSecond(duration)
                self.vdduration['text']=duration
            else:
                tkinter.messagebox.showerror("提示","请选择音频文件")
    
        '''获取音频提取的存放路径'''
    def getaudio2Path(self):
        path = filedialog.askdirectory()
        if path !="":
            self.audio2String.set(path)
    
    '''选取开始时间'''
    def getStartScale(self,v):
        if self.d_second != None:
            unit = self.d_second/100.0
            v = float(v)
            self.startShowLabel['text']=mediaUtil.getHMS(int(unit*v))
    
    '''选取结束时间'''
    def getEndScale(self,v):
        if self.d_second != None:
            unit = self.d_second/100.0
            v = float(v)
            self.endShowLabel['text']=mediaUtil.getHMS(int(unit*v))
    
    '''剪切音频'''        
    def audioCut(self):
        try:
            audioPath = self.audioString.get()
            if audioPath == "":
                tkinter.messagebox.showerror("提示","请选择音频文件")
                return False
            audio2Path = self.audio2String.get()
            if audio2Path =="":
                tkinter.messagebox.showerror("提示","请选择存放文件夹")
                return False
            audioName = os.path.basename(audioPath)
            ret = list(re.finditer('\.', audioName))
            audioName = audioName[0:ret[-1].span()[0]]
            ext = os.path.splitext(audioPath)[1][1:]
            outputFile = audio2Path+'/{0}.{1}'.format(audioName,ext)
            cmd = mediaUtil.cmd_audioSimpleCut(audioPath, self.startTime.get(), self.endTime.get(), outputFile)
            if cmd is None:
                tkinter.messagebox.showerror("提示","无法获取音频剪切命令")
            self.statusLabel['text']='剪切中'
            subprocess.Popen(cmd)
            #禁用剪切按钮
            self.execBtn.config(state=DISABLED)
            cut_thread = threading.Thread(target=self.getCutProgress,args=(None,cmd))
            cut_thread.start()
        except:
            self.statusLabel['text']='剪切失败'
            print(sys.exc_info())
    
    '''获取剪切进度'''
    def getCutProgress(self,x,cmd):
        try:
            iscomplete = 0
            while iscomplete ==0:
                info = mediaUtil.getCmdExecInfo(cmd)
                if info !="":
                    iscomplete=1
            if iscomplete ==1:
                self.statusLabel['text']='剪切成功'
            #启用剪切按钮
            self.execBtn.config(state=NORMAL)
        except:
            self.statusLabel['text']='剪切失败'